package com.qianya.system.face.web.patient.service.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mysql.cj.xdevapi.JsonArray;
import com.qianya.model.common.BaseEntity;
import com.qianya.model.pojo.patient.vo.CalendarVo;
import com.qianya.model.pojo.patient.vo.PatientBoxRelevanceVO;
import com.qianya.system.face.web.patient.model.PatientBoxRelevance;
import com.qianya.system.face.web.patient.service.IPatientBoxRelevanceService;
import com.qianya.system.face.web.patient.mapper.PatientBoxRelevanceMapper;
import com.qianya.util.DateUtils;
import org.springframework.stereotype.Service;
import com.qianya.model.common.CommonResult;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.qianya.model.common.ResultCode;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
* <p>
*  患者绑定发药柜服务实现类
* </p>
*
* @author lhl
* @since 2020-07-22
*/
@Service
public class PatientBoxRelevanceServiceImpl extends ServiceImpl<PatientBoxRelevanceMapper, PatientBoxRelevance> implements IPatientBoxRelevanceService {
        @Resource
        private PatientBoxRelevanceMapper boxRelevanceMapper;
        /**
        *查找 患者绑定发药柜
        * @author lhl
        * @since 2020-07-22
        */
        @Override
        public CommonResult find(PatientBoxRelevance patientBoxRelevance) {
            IPage iPage = null;
            return CommonResult.success(list());
        }
        /**
        * 新增 患者绑定发药柜
        * @author lhl
        * @since 2020-07-22
        */
        @Override
        public CommonResult create(PatientBoxRelevance patientBoxRelevance,HttpServletRequest request) {
            boolean b = save(patientBoxRelevance);
            if (b){
                return CommonResult.success();
            }
            return CommonResult.error(ResultCode.ERROR,"操作失败");
        }
    /**
     * @desc 服药异常统计
     * @author lhl
     * @date 2020-07-24 11:26
     * @return
    */
    @Override
    public int eatExceptionCount() {
        Calendar calendar=Calendar.getInstance();
        int hours=calendar.get(calendar.HOUR_OF_DAY);
        List<String> list= DateUtils.theThreeTimeQuantum();
        QueryWrapper<PatientBoxRelevance> queryWrapper=new QueryWrapper<PatientBoxRelevance>();
        queryWrapper.eq("br_state",1);  //所有未发药的人
        if (hours<8){
            queryWrapper.lt("create_time",list.get(0));
        }else if (hours<12){
            queryWrapper.lt("create_time",list.get(1));
        }else if (hours<18){
            queryWrapper.lt("create_time",list.get(2));
        }else {
            queryWrapper.lt("create_time",list.get(3));
        }
        return count(queryWrapper);
    }
    /**
     * @desc 服药异常列表
     * @author lhl
     * @date 2020-07-24 11:26
     * @return
     */
    @Override
    public CommonResult eatException() {
        Calendar calendar=Calendar.getInstance();
        int hours=calendar.get(calendar.HOUR_OF_DAY);
        List<String> list= DateUtils.theThreeTimeQuantum();
        List<PatientBoxRelevanceVO> listBox=null;
        if (hours<8){
            listBox=boxRelevanceMapper.eatException(list.get(0));
        }else if (hours<12){
            listBox=boxRelevanceMapper.eatException(list.get(1));
        }else if (hours<18){
            listBox=boxRelevanceMapper.eatException(list.get(2));
        }else {
            listBox=boxRelevanceMapper.eatException(list.get(3));
        }
        for (int i = 0; i <listBox.size() ; i++) {
            listBox.get(i).setUpdateTime(this.timeTrans(listBox.get(i).getCreateTime()));
        }
        return CommonResult.success(listBox);
     }

         /**
        * 修改 患者绑定发药柜
        * @author lhl
        * @since 2020-07-22
        */
        @Override
        public CommonResult renewal(PatientBoxRelevance patientBoxRelevance,HttpServletRequest request) {
            boolean b = updateById(patientBoxRelevance);
            if (b){
                return CommonResult.success();
            }
            return CommonResult.error(ResultCode.ERROR,"操作失败");
        }
        /**
         * @desc 时间转换
         * @author lhl
         * @date 2020-07-24 15:43
         * @return
        */
        public Date timeTrans(Date time){
            SimpleDateFormat sdf=new SimpleDateFormat("HH");
            Calendar cal=Calendar.getInstance();
            cal.setTime(time);
            Integer hours=Integer.valueOf(sdf.format(time));
            if (hours<8){
                cal.set(Calendar.HOUR_OF_DAY, -6);
                cal.set(Calendar.MINUTE, 0);
                cal.set(Calendar.SECOND, 0);
            }else if (hours<12){
                cal.set(Calendar.HOUR_OF_DAY, 8);
                cal.set(Calendar.MINUTE, 0);
                cal.set(Calendar.SECOND, 0);
            }else if (hours<18){
                cal.set(Calendar.HOUR_OF_DAY, 12);
                cal.set(Calendar.MINUTE, 0);
                cal.set(Calendar.SECOND, 0);
            }else {
                cal.set(Calendar.HOUR_OF_DAY, 18);
                cal.set(Calendar.MINUTE, 0);
                cal.set(Calendar.SECOND, 0);
            }

            return cal.getTime();
        }
    /**
     * @desc 患者服药记录
     * @author lhl
     * @date 2020-07-27 10:08
     * @return
     */
    @Override
    public CommonResult takeMedicineRecode(int pageNo,int pageSize,String fileIdentityCard) {

        List<String> timeList=DateUtils.theThreeTimeQuantum();
        List<PatientBoxRelevanceVO> oldList=boxRelevanceMapper.takeMedicineRecode(pageNo,pageSize,fileIdentityCard,timeList.get(0));

        return CommonResult.success(oldList);
    }
    /**
     * @desc  日历查询患者服药日志
     * @author lhl
     * @date 2020-08-07 09:37
     * @return
    */
    @Override
    public CommonResult takeMedicineCalendarRecode(String fileIdentityCard) {
        List<PatientBoxRelevance> list=list(new QueryWrapper<PatientBoxRelevance>().eq("file_identity_card",fileIdentityCard).ne("br_state",0));
        Map<String,String> map=new HashMap<>();
        for (int i = 0; i < list.size(); i++) {
            String time=this.timeChange(list.get(i).getCreateTime());
           if(map.containsKey(time)){
               if (list.get(i).getBrState()==1){
                   map.put(time,"存在异常");
               }
           }else {
               map.put(time,list.get(i).getBrState()==1?"存在异常":"解除预警");
           }
        }
        List<CalendarVo> cvList=new ArrayList<>();
        CalendarVo cv=null;
        for (Map.Entry<String, String> entry : map.entrySet()) {
            cv=new CalendarVo();
            cv.setData(entry.getKey());
            cv.setContent(entry.getValue());
            cvList.add(cv);
        }
        return CommonResult.success(cvList);
    }
    /**
     * @desc 解除预警
     * @author lhl
     * @date 2020-08-10 08:53
     * @return
    */
    @Override
    public CommonResult cancelWarning(String brId) {
        PatientBoxRelevance pbr=getById(brId);
        if (pbr==null){
            return CommonResult.error(ResultCode.OTHER_EXCEPTION,"不存在的id");
        }
        if (pbr.getBrState()==0){
            return CommonResult.error(ResultCode.OTHER_EXCEPTION,"该次已正常发药，无法解除预警");
        }
        if (pbr.getBrState()==2){
            return CommonResult.error(ResultCode.OTHER_EXCEPTION,"请勿重复操作");
        }
        pbr.setBrState(2);
        pbr.setBrId(brId);
        if (updateById(pbr)){
            return CommonResult.success();
        }
        return CommonResult.error(ResultCode.ERROR,"操作失败");
    }

    /**
     * @desc 根据一个时间查询 时间段
     * @author lhl
     * @date 2020-07-27 15:05
     * @return
    */
    public static List<String> getTime(String endTime,int pageSize){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sdfss = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Long thisDate=sdf.parse(endTime).getTime();
            Long end=thisDate-21600000l;
            Long start=end-pageSize*86400000l;
            List<String> listTime=new ArrayList<String>();
            listTime.add(sdfss.format(DateUtil.date(start)));
            listTime.add(sdfss.format(DateUtil.date(end)));
            return listTime;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * @desc 根据放药时间段判断这药该哪天吃
     * @author lhl
     * @date 2020-08-07 13:45
     * @return
    */
    public String timeChange(Date time){
        SimpleDateFormat sdf=new SimpleDateFormat("HH");
        Integer hours=Integer.valueOf(sdf.format(time));
        Long longTime=time.getTime();
        if (hours>=18){
            longTime=longTime+43200000l;
        }
        SimpleDateFormat sdf2=new SimpleDateFormat("yyyy-MM-dd");
        return sdf2.format(new Date(longTime));
    }
}
